package 网络编程.TCPECHOBITE;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class TCPEchoServer {

    //TCP版本的回显服务器
    private ServerSocket serverSocket = null;
    public TCPEchoServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }
    public void start() throws IOException {
        System.out.println("服务器启动!!!");
        while(true){
            //相当于服务器接到连接(监听) 把连接交给socket为客户端提供服务
            Socket clintSocket = serverSocket.accept();
            processService(clintSocket);
        }
    }

    public void processService(Socket clintSocket) throws IOException {
        System.out.printf("建立连接 [%s:%d]\n",
                clintSocket.getInetAddress().toString()
                , clintSocket.getPort());
        try(InputStream inputStream = clintSocket.getInputStream();
            OutputStream outputStream = clintSocket.getOutputStream()) {
            Scanner scan = new Scanner(inputStream);
            PrintWriter printWriter = new PrintWriter(outputStream);
            while (true) {
                if(!scan.hasNext()){
                    System.out.printf("断开连接 [%s:%d]\n",
                            clintSocket.getInetAddress().toString()
                            , clintSocket.getPort());
                    break;
                }
                //接收请求并解析
                String request = scan.next();
                //根据请求计算响应
                String response = process();
                //将响应发送给客户端
                printWriter.println(response);
                printWriter.flush();
                System.out.printf("[%s:%d] req = %s ; resp = %s\n",
                        clintSocket.getInetAddress().toString()
                        , clintSocket.getPort(), request, response);
            }
        } finally {
            clintSocket.close();
        }
    }

    public String process(){
        //回显服务器,接收到了啥就返回啥
        String response = "hello,clint";
        return response;
    }

    public static void main(String[] args) throws IOException {
        TCPEchoServer tcpEchoServer = new TCPEchoServer(8000);
        tcpEchoServer.start();
    }
}
